package com.kuiandjie.web;


import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.kuiandjie.entity.Employee;
import com.kuiandjie.entity.Log;
import com.kuiandjie.entity.Project;
import com.kuiandjie.service.EmployeeService;
import com.kuiandjie.service.SendMsgService;

public class SendMsgServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		if("POST".equals(request.getMethod())) {
			HttpSession session = request.getSession();
			Project curp = (Project) session.getAttribute("curp");
			if(curp != null) {
				Employee e = (Employee) session.getAttribute("employee");
				String content = request.getParameter("content");
				if(content.startsWith("@")) {
					String[] array = content.split(" ");
					
					int me = e.getId();
					int at = 0;
					if(array.length == 2) {
						Employee emp = new EmployeeService().getEmoloyeeByName(array[0].substring(1));
						if(emp != null) {
							at = emp.getId();
							content = array[0] + ":" + array[1];
						} else {
							content = array[0] + "未找到！";
						}
					} else {
						content = "格式有误";
					}
					
					request.setAttribute("me", me);
					request.setAttribute("at", at);
				} 
				SendMsgService sms = new SendMsgService();
				Log log = sms.addMessage(e.getId(), curp.getId(), content, e.getName(), e.getPic());
				request.setAttribute("msg", new Gson().toJson(log));
				request.getRequestDispatcher("msgflow.jspx").include(request, response);
			}
		}
	}
	
	
}
